package com.hhx.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;

/**
 * 文件操作
 * @author 非灭天
 *
 */
public class FileOperate {
	private static String[] af=null;
	/**
	 * 文件保存路径
	 */
	public static String excelSavePath = "./export.xls";
	
	/**
	 * 得到文件保存路径
	 * @return
	 */
	public static String getExcelSavePath() {
		return excelSavePath;
	}
    
	/**
	 * 设置文件保存路径
	 * @param excelSavePath
	 */
	public static void setExcelSavePath(String excelSavePath) {
		FileOperate.excelSavePath = excelSavePath;
	}

	/**
	 * 工作表总数
	 */
	private static int sheetIndexTest = 1;
	/**
	 * 最大行
	 */
	private int rowIndexTest = 4;
	/**
	 * 最大列
	 */
	private int colIndexTest = 6;

	
	
	/**
	 * 读取文件
	 * @param fname
	 * @return
	 */
	public static String readFile(String fname) {
		String content = "";
		try {
			BufferedReader br = new BufferedReader(new BufferedReader(new InputStreamReader(new FileInputStream(new File(fname)),"utf-8")));
			while (br.ready()) {
				String s = br.readLine();
				if("".equals(content))
				{
				  content=s;
				}else{
				  content += s ;
				}
			}
			br.close();
		} catch (Exception ex) {
		}

		return content;
	}
	/**
	 * 读取目录内所有文件
	 * @param strv 路径
	 * @return String[]
	 */
	public static String[] readAllFilesinDirectory(String strv) {
		File f = new File(strv);
		if(f.list()!=null){
		String fs[] = f.list();	
		af=new String[fs.length];
			for (int i = 0; i < fs.length; i++) {				
				File fv = new File(fs[i]);
				if (fv.canWrite()) {
					break;
				} else {
					try {
						System.out.println(f.getCanonicalPath() + fs[i]);
						af[i]=fs[i];
//						VskVmethodBody.readAllDirectory(f.getCanonicalPath() + fs[i]);						
					} catch (Exception e) {						
						e.printStackTrace();
					}
				}
			}
		}
		return af;
	}
	/**
	 * 传入二维数组 写成excel文件
	 * write excel to file
	 */
	public static void writeExcel(String[][] inArray) {
		try {
			if(inArray==null){
				inArray=new String[0][0];
			}
			// 创建新工作薄　
			// create new Excel workbook 　
			HSSFWorkbook workbook = new HSSFWorkbook();
			for (int sheetIndex = 0; sheetIndex < sheetIndexTest; sheetIndex++) {
				// 在工作薄中创建工作表 sheet X 　　
				// create new sheet in workbook
				HSSFSheet sheet = workbook.createSheet("sheet" + sheetIndex);
				// HSSFSheet sheet = workbook.createSheet();
				for (int rowIndex = 0; rowIndex < inArray.length; rowIndex++) {
					// 在工作表中创建行
					// create row in sheet
					HSSFRow row = sheet.createRow(rowIndex);
					for (int colIndex = 0; colIndex < inArray[0].length; colIndex++) {
						// 在索引rowIndex的位置创建单元格（左上端）
						// create column in row
						HSSFCell cell = row.createCell(colIndex);
						// 定义单元格为字符串类型 　　
						// set the cell data type
						cell.setCellType(HSSFCell.CELL_TYPE_STRING);
						// 在单元格中输入一些内容
						// set the cell data
						cell.setCellValue(inArray[rowIndex][colIndex]);
					}// end for colIndex
				}// end for rowIndex
			}// end for sheetIndex
			// 新建一输出文件流
			// new FileOutputStream
			FileOutputStream fOut = new FileOutputStream(excelSavePath);
			// 把相应的Excel 工作簿存盘
			// save the excel workbook
			workbook.write(fOut);
			fOut.flush();
			// 操作结束，关闭文件
			// finish operate close file
			fOut.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}// end method writeExcel

	/**
	 * 删除文件
	 * 
	 * @param fname
	 */
	public static void deleteFile(String fname) {
		// System.out.println(fname);
		(new File(fname)).delete();
	}
	
	public static String getDBConfig(String fname){		
		return FileOperate.readFile(fname);
		
	}
	
	/**
	 * 读取excel文件
	 * @param inFile 文件路径
	 * read excel file
	 */
	public static String[][] readExcel(String inFile) {
		String[][] tempArray=null;
		try {
			// read the workbook in file
			HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(inFile));
			// get the sheet in workbook
			// HSSFSheet sheet = workbook.getSheet("Sheet0");
			//得到excel内工作表总数
			int sheetIndexTest=workbook.getNumberOfSheets();
			
			for (int sheetIndex = 0; sheetIndex < sheetIndexTest; sheetIndex++) {
				// you can use getSheetAt(int index) get the sheet in workbook
				// 也可用getSheetAt(int index)按索引引用
				HSSFSheet sheet = workbook.getSheetAt(sheetIndex);
				//得到工作表内行数
				int rowIndexTest=sheet.getPhysicalNumberOfRows();
				for (int rowIndex = 0; rowIndex < rowIndexTest; rowIndex++) {
					HSSFRow row = sheet.getRow(rowIndex);
					//得到列数
					int colIndexTest=row.getLastCellNum();
					for (int colIndex = 0; colIndex < colIndexTest; colIndex++) {
						HSSFCell cell = row.getCell(colIndex);
						if(tempArray==null){
							tempArray=new String[rowIndexTest][colIndexTest];
						}
						//System.out.print("["+rowIndex + ":" + colIndex + "||"	+ cell.getStringCellValue()+"]");
						tempArray[rowIndex][colIndex]=(String)(cell.getStringCellValue()==null?cell.getNumericCellValue():cell.getStringCellValue());
					}// end for colIndex
					//System.out.println();
				}// end for rowIndex
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return tempArray;

	}// end method readExcel

	 /**
     * 创建文件
     * @param destFileName 文件名称
     * @return
     */
    public static boolean CreateFile(String destFileName) {
        File file = new File(destFileName);
        if (file.exists()) {
            System.out.println("创建单个文件" + destFileName + "失败，目标文件已存在！");
            return false;
        }
        if (destFileName.endsWith(File.separator)) {
            System.out.println("创建单个文件" + destFileName + "失败，目标不能是目录！");
            return false;
        }
        if (!file.getParentFile().exists()) {
           // System.out.println("目标文件所在路径不存在，准备创建。。。");
            if (!file.getParentFile().mkdirs()) {
               // System.out.println("创建目录文件所在的目录失败！");
                return false;
            }
        }

        // 创建目标文件
        try {
            if (file.createNewFile()) {
               // System.out.println("创建单个文件" + destFileName + "成功！");
                return true;
            } else {
                System.out.println("创建单个文件" + destFileName + "失败！");
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("创建单个文件" + destFileName + "失败！");
            return false;
        }
    }//end method create method

    /**
     * 创建目录
     * @param destDirName 目录名称
     * @return boolean
     */
    public static boolean createDir(String destDirName) {
        File dir = new File(destDirName);
        if (dir.exists()) {
           System.out.println("创建目录" + destDirName + "失败，目标目录已存在！");
            return false;
        }
        if (!destDirName.endsWith(File.separator)) {
            destDirName = destDirName + File.separator;
        }
        // 创建单个目录
        if (dir.mkdirs()) {
           // System.out.println("创建目录" + destDirName + "成功！");
            return true;
        } else {
           // System.out.println("创建目录" + destDirName + "成功！");
            return false;
        }
    }//end method createDir

    /**
     * 3*. 从输入流中拷贝内容到输入流中
     * @throws IOException
     */
    public void copyStream(InputStream is, OutputStream os) {
        try {
            // 这个读过过程可以参阅 readToBuffer 中的注释
            String line;
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            PrintWriter writer = new PrintWriter(new OutputStreamWriter(os));
            line = reader.readLine();
            while (line != null) {
                writer.println(line);
                line = reader.readLine();
            }
            writer.flush();     // 最后确定要把输出流中的东西都写出去了
        } catch (Exception e) {
            e.printStackTrace();
        }
    }//end copyStream method

    /**
     * 复制文件
     * @param inFilename 源文件
     * @param outFilename 目标文件
     */
    public void copyFile(String inFilename, String outFilename) {
        try {
            // 先根据输入/输出文件生成相应的输入/输出流
            InputStream is = new FileInputStream(inFilename);
            OutputStream os = new FileOutputStream(outFilename);
            copyStream(is, os);     // 用 copyStream 拷贝内容
            is.close(); // is 是在这里打开的，所以需要关闭
            os.close(); // os 是在这里打开的，所以需要关闭
        } catch (Exception e) {
            e.printStackTrace();
        }
    }//end method copyFile
    
    public static boolean isExistsDir(String inDir)
    {
    	return new File(inDir).exists();
    }
    
	/**
	 * @param args
	 */
	public static void main(String[] args) {
	}//end main method

}//end class 
